program main
implicit none

 character(len=99)buffer,maplist,trjpdb,output
 character(len=99)buffer1
 character(len=20),dimension(20) :: col
integer i,j,k,ios,totframe,nargs,connum,resi,resj,l,m,n,transNum,h1,s,h2
integer,parameter :: Contactnumber=9999
integer,parameter :: closeca=196
integer :: c1(Contactnumber)
integer :: c2(Contactnumber)
real :: Q(Contactnumber),Qnative1,Qnative2,Qnative3,dist,P(closeca,closeca,2)
real,parameter :: cutoff=7.0
real :: x(closeca)
real :: y(closeca)
real :: z(closeca)
real :: d(Contactnumber)
real :: R0(Contactnumber)
real,parameter :: MULTI=1.2

 nargs=iargc()
   if(nargs==3)then
      call getarg(1,maplist)
      call getarg(2,trjpdb)
      call getarg(3,output)
   else
      write(*,*) "Wrong Input!"
      write(*,*) "Usage: /xx.x  contactmaplist  trjpdb   outputfile"
      write(*,*) "Usage: /xx.x  inter-pairs.list  traj_tmp.pdb   Bsequence.list"
      goto 1000
   endif

ios=0
i=0
open(10,file=maplist,status="old")
do while(.true.)
 read(10,"(A)",iostat=ios)buffer
 if(ios/=0)exit
 i=i+1
 read(buffer,*)(col(k),k=1,3)
 read(col(1),"(I5)") resi
 read(col(2),"(I5)") resj
 read(col(3),"(F10.7)") dist
 c1(i)=resi
 c2(i)=resj
 R0(i)=dist
end do
close(10)

 connum=i
    write(*,*) connum
ios=0
k=0
transNum=0
!Qnative=0
open(20,file=trjpdb,status="old")
open(30,file=output,status="replace")
do while(.true.)
 read(20,"(A)",iostat=ios)buffer
  if(ios/=0)exit
  if(buffer(1:5)=="MODEL")then
   i=0
   k=k+1
    if(mod(k,1000)==0)then
      write(*,*) k
    endif
   Qnative1=0
   Qnative2=0
   Qnative3=0
    do while(.true.)
     read(20,"(A)")buffer
      if(buffer(1:3)=="TER")exit
      if(buffer(14:14)=="C")then
        i=i+1
       read(buffer(32:38),"(F)") x(i)
       read(buffer(40:46),"(F)") y(i)
       read(buffer(48:54),"(F)") z(i)
      end if
    end do
    do j=1,20
     d(j)=sqrt((x(c2(j))-x(c1(j)))**2+(y(c2(j))-y(c1(j)))**2+(z(c2(j))-z(c1(j)))**2)
      if(d(j)<MULTI*R0(j))then
          Qnative1=Qnative1+1.0
      endif
    end do
    do j=21,33
     d(j)=sqrt((x(c2(j))-x(c1(j)))**2+(y(c2(j))-y(c1(j)))**2+(z(c2(j))-z(c1(j)))**2)
      if(d(j)<MULTI*R0(j))then
          Qnative2=Qnative2+1.0
      endif
    end do
    do j=34,45
     d(j)=sqrt((x(c2(j))-x(c1(j)))**2+(y(c2(j))-y(c1(j)))**2+(z(c2(j))-z(c1(j)))**2)
      if(d(j)<MULTI*R0(j))then
          Qnative3=Qnative3+1.0
      endif
    end do
!       write(30,"(I,3X,F15.9)") k,Qnative/connum
          h1=0;s=0;h2=0
       if(Qnative1>20*0.8)then
         h1=1
       endif
       if(Qnative2>13*0.8)then
         s=1
       endif
       if(Qnative3>12*0.8)then
         h2=1
       endif
        write(30,*) k,h1,s,h2
 endif
enddo
close(20)
close(30)
1000 end program
